/*
    AuthorNote: ***
    Created By: Bambom Date:DATE
*/

using Table.Blo;
using UnityEngine;

namespace AutoChess
{
    /// <summary>
    /// 存放hero表现相关的逻辑。 主要是让代码更整洁可控
    /// </summary>
    class ACHeroBehaviorCmpt:ActorCmpt
    {
        protected override void Awake()
        {
            AddEventListener<ACGrid,ACGrid,bool>(ActorEventType.ACActorEnterGridBehavior,OnACActorEnterGridBehavior);
        }
        
        /// <summary>
        /// 英雄销毁时候同时需要离开这个格子
        /// </summary>
        protected override void OnDesstroy()
        {
            OwnActor.Event.SendEvent(ActorEventType.ACActorLeaveGrid);
        }

        /// <summary>
        /// 英雄进入格子的行为表现:特效、动作、状态等行为逻辑
        /// </summary>
        private void OnACActorEnterGridBehavior(ACGrid fromGrid,ACGrid toGrid,bool refreshModelTransform)
        {
            UpdatePostion(toGrid.Position);
            if (fromGrid == null || fromGrid.GridType == GridType.ShopGrid)
            {
                RefreshHeroParentToGrid(toGrid);
                if (refreshModelTransform)
                {
                    AutoChessManager.Ins.ShotFootPrintEffect(toGrid);
                }
            }
            else
            {
                AutoChessManager.Ins.ShotFootPrintEffect(toGrid);
                if (toGrid.GridType == GridType.FightGrid)
                {
                    AutoChessManager.Ins.CurrentAutoChessField.AutoUpgradeStarMsg(toGrid);
                }
                ActorEventHelper.SendActorStateChange(OwnActor,ActorStateEvent.Actor_Appearance);
            }
            
            //更新模型位置状态显示等
            if (refreshModelTransform)
                RefreshModelOffset(OwnActor as ACHero);
        }

        private void RefreshHeroParentToGrid(ACGrid toGrid)
        {
            OwnActor.Display.RefreshModelLayer(LayerName.UI);
            transform.SetParent(toGrid.ActorGo.transform);
            transform.Normalize();
        }

        private void UpdatePostion(Vector3 position)
        {
            transform.position = position;
        }
        
        private void RefreshModelOffset(ACHero heroUnit)
        { 
            Vector3 pos, scale, angle;
            var grid = heroUnit.MapGrid;
            UtilityHelper.TryGetHerooffset(heroUnit.HeroID,grid.GridType,out pos,out scale , out angle);
            ActorEventHelper.SendActorModelOffsetUpdate(heroUnit,pos,scale,angle);
        }
    }
}